class DslersController < ApplicationController
  attr_reader :title 
  attr_reader :validation_msg
  attr_reader :validate_field
  attr_reader :dsler

  before_filter :authorize, :except => [:create, :signup, :login, :validate_name, :validate_email]

    def authorize
      unless session[:dsler_id]
        flash[:notice] = "Please log in"
        redirect_to :action => "login"
      end
    end


  def index
    render :action => 'list'
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @dsler_pages, @dslers = paginate :dslers, :per_page => 10
  end

  def show
    @dsler = Dsler.find(params[:id])
    render :action => 'edit'
  end

  def signup
    @title = 'Sign Up As DSLer - DSL Forge'
    @dsler = Dsler.new
  end

  def create
    @dsler = Dsler.new(params[:dsler])
    if @dsler.save
      flash[:notice] = 'Welcome '+@dsler.name+'. Your account has been created successfully.'
      redirect_to :controller=>'home', :action => 'index'
    else
      render :action => 'signup'
    end
  end

  def validate_email
    @dsler = Dsler.new({:email => params[:dsler_email]})
    @dsler.valid? 
    @validation_msg=@dsler.errors.on "email"
    @validate_field="email"
    if (@validation_msg == nil || @validation_msg == '')
        render :layout => false, :action => 'validate_succeed'
    else
        render :layout => false, :action => 'validation_result'
    end
  end

  def validate_name
    @dsler = Dsler.new({:name => params[:dsler_name]})
    @dsler.valid?
    @validation_msg=@dsler.errors.on "name"
    @validate_field="name"
    if (@validation_msg == nil || @validation_msg == '')
        render :layout => false, :action => 'validate_succeed'
    else
        render :action => 'validation_result', :layout=>false
    end
  end

  def edit
    @dsler = Dsler.find(params[:id])
  end

  def update
    @dsler = Dsler.find(params[:id])

    if @dsler.update_attributes(params[:dsler])
      flash[:notice] = 'Dsler was successfully updated.'
      redirect_to :action => 'show', :id => @dsler
    else
      render :action => 'edit'
    end
  end

  def destroy
    Dsler.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

  def login
     @dsler = Dsler.find_by_email_and_password(params[:dsler_email], params[:dsler_password])
     puts @dsler
     if @dsler
        session[:dsler_id] = dsler.id
        session[:dsler_name] = dsler.name
        session[:dsler_email] = dsler.email
     else
        reset_session
        flash[:note] = "Invalid user name/password"
     end
     render :action => 'login_result', :layout=>false
  end
end
